package cn.wen233.srpc.basic.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;

/**
 * IO 工具类
 *
 * @author wenei
 * @date 2021-10-27 20:33
 */
public class IoUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(IoUtils.class);

    public static byte[] inputStreamToByteArray(InputStream inputStream) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 4];
        byte[] result = null;
        try {
            while (inputStream.read(buffer) != -1) {
                outputStream.write(buffer);
            }
            result = outputStream.toByteArray();
            closeQuietly(outputStream);
        } catch (IOException e) {
            LOGGER.warn("InputStream 转化为 byte数组时出现错误", e);
        }
        return result;
    }

    public static void closeQuietly(HttpURLConnection connection) {
        if (connection != null) {
            try {
                closeQuietly(connection.getInputStream());
            } catch (IOException e) {
            }
        }
    }

    public static void closeQuietly(InputStream input) {
        closeQuietly((Closeable) input);
    }

    public static void closeQuietly(OutputStream output) {
        closeQuietly((Closeable) output);
    }

    /**
     * 安静的关闭，不打印相关日志信息
     */
    public static void closeQuietly(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {

            }
        }
    }
}
